#!/bin/sh
# 源码安装Ipvsadm -- 管理LVS
App=ipvsadm
AppName=Ipvsadm
Kernel="$(uname -r)-$(uname -m)"
NIC=eth0:0
AppProg=$(which ipvsadm)
VIP=192.168.100.200
RIP1=192.168.100.103
RIP2=192.168.100.104
AppCodeRoot=/App/src
AppCodeDir=$(find $AppCodeRoot -maxdepth 1 -name "$App-*.tar.*" -type f 2> /dev/null | sed -e 's/.tar.*$//' -e 's/^.\///')
KernelDir=/usr/src/kernels/$(ls /usr/src/kernels/)

fstatus()
{
    $AppProg -ln
}

finstall()
{
    which $AppProg &> /dev/null

    if [ "$?" -eq 0 ]; then
        echo "$AppName 已安装"
    else
        freinstall
    fi
}

freinstall()
{
    if [ -d "/usr/src/linux" -o -L "/usr/src/linux" ]; then
        echo "/usr/src/linux 已存在"
    else
        ln -sv $KernelDir /usr/src/linux
    fi

    yum -y install libnl* popt*
    cd $AppCodeRoot
    test -d "$AppCodeDir" && rm -rf $AppCodeDir

    tar axf $App-*.tar.*
    cd $AppCodeDir
    make && make install

    if [ "$?" -eq 0 ]; then
        echo "$AppName 安装成功"
    else
        echo "$AppName 安装失败"
    fi
}

fstart()
{
    echo "启动 LVS"

    ifconfig $NIC $VIP broadcast $VIP netmask 255.255.255.255 up
    route add -host $VIP dev $NIC
    
    $AppProg -A -t $VIP:80 -s wrr -p 3
    $AppProg -a -t $VIP:80 -r $RIP1:80 -g -w 1
    $AppProg -a -t $VIP:80 -r $RIP2:80 -g -w 1
}

fstop()
{
    echo "停止 LVS"    

    $AppProg -C
    $AppProg -Z
    ifconfig $NIC down
}

ScriptFile=$(basename $0)
case "$1" in
    "status"    ) fstatus;;
    "install"   ) finstall;;
    "reinstall" ) freinstall;;
    "start"     ) fstartf;;
    "stop"      ) fstop;;
    "restart"   ) fstop && fstart;;
    * )
        echo "$ScriptFile status               查询 LVS 状态"
        echo "$ScriptFile install              安装 $AppName"
        echo "$ScriptFile reinstall            重装 $AppName"
        echo "$ScriptFile start                启动 LVS"
        echo "$ScriptFile stop                 停止 LVS"
        echo "$ScriptFile restart              重启 LVS"
        ;;
esac
